﻿using ASP.NET_MVC5_Bootstrap3_3_1_LESS.Models;
using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using WebApp;

namespace ASP.NET_MVC5_Bootstrap3_3_1_LESS.Controllers
{
    public class HomeController : Controller
    {        
        public ActionResult HideNavHelp()
        {
            Session["hideNavHelp"] = "hide";

            return RedirectToAction("Index");
        }

        public ActionResult Content(NavModel wModel)
        {
            if (Session["FBUserID"] != null)
            {
                HttpCookie cookie = new HttpCookie("FBUserID", Session["FBUserID"].ToString());
                this.ControllerContext.HttpContext.Response.AppendCookie(cookie);                                     
            }
            if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("FBUserID"))
            {
                Session["PlayerID"] = this.ControllerContext.HttpContext.Request.Cookies["FBUserID"].Value;
            }

            if (SiteStructure.Instance == null) SiteStructure.Instance = new SiteStructure(Server.MapPath("~/Content/Word2Boot"));
            SiteStructure.Instance.Update();
            
            ViewBag.mi = wModel.mi;
            return View(wModel);
        }


        public ActionResult Index()
        {
            NavModel wModel = new NavModel();
            if (SiteStructure.Instance == null) SiteStructure.Instance = new SiteStructure(Server.MapPath("~/Content/Word2Boot"));
            SiteStructure.Instance.Update();
            
            return View(wModel);
        }

        public ActionResult About()
        {
            if (SiteStructure.Instance == null) SiteStructure.Instance = new SiteStructure(Server.MapPath("~/Content/Word2Boot"));
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            if (SiteStructure.Instance == null) SiteStructure.Instance = new SiteStructure(Server.MapPath("~/Content/Word2Boot"));
            ViewBag.Message = "Your contact page.";

            return View();
        }

        static FileSystemWatcher fw = null;

        static object mSyncLock = new object();
        static public void Sync(string wContentPath)
        {
            lock (mSyncLock)
            {
                try
                {
                    // look though drop box location and copy over files
                    if (fw == null)
                    {
                        fw = new FileSystemWatcher(SiteStructure.GetRoot() + "\\");
                        fw.IncludeSubdirectories = true;
                        fw.EnableRaisingEvents = true;
                    }
                    
                    fw.Changed -= fw_Changed;
                    fw.Created -= fw_Created;
                    fw.Deleted -= fw_Deleted;
                    fw.Renamed -= fw_Renamed;

                    string wfileLoc = SiteStructure.GetRoot();
                    CreateDirectories(wfileLoc, wContentPath, wContentPath);
                }
                finally
                {
                    try
                    {
                        fw.Changed += fw_Changed;
                        fw.Created += fw_Created;
                        fw.Deleted += fw_Deleted;
                        fw.Renamed += fw_Renamed;
                    }
                    catch { }
                }
            }
        }

        static void fw_Renamed(object sender, RenamedEventArgs e)
        {
            if (e == null || e.FullPath == null || e.FullPath.Contains("web_thumbs") || e.FullPath.Contains("web_images")) return;
            RegChanged();
        }

        static void fw_Deleted(object sender, FileSystemEventArgs e)
        {
            if (e == null || e.FullPath == null || e.FullPath.Contains("web_thumbs") || e.FullPath.Contains("web_images")) return;
            RegChanged();
        }

        public static bool changed = true;
        static void fw_Created(object sender, FileSystemEventArgs e)
        {
            if (e == null || e.FullPath == null || e.FullPath.Contains("web_thumbs") || e.FullPath.Contains("web_images")) return;
            RegChanged();
        }

        static void fw_Changed(object sender, FileSystemEventArgs e)
        {
            if (e == null || e.FullPath == null || e.FullPath.Contains("web_thumbs") || e.FullPath.Contains("web_images")) return;
            RegChanged();
        }

        static void RegChanged()
        {
            changed = true;
        }

        static private void CreateDirectories(string wSrc, string wDst, string wContentPath)
        {
            // remove folders that begin with mi-
            foreach (string wDir in Directory.GetDirectories(wDst, "mi-*"))
            {
                Directory.Delete(wDir, true);
            }

            foreach (string wFile in Directory.GetFiles(wDst, "home-*"))
            {
                System.IO.File.Delete(wFile);
            }

            foreach (string wFile in Directory.GetFiles(wDst, "*.jpg")) { System.IO.File.Delete(wFile);    }
            foreach (string wFile in Directory.GetFiles(wDst, "*.jpeg")) { System.IO.File.Delete(wFile); }
            foreach (string wFile in Directory.GetFiles(wDst, "*.png")) { System.IO.File.Delete(wFile); }
            foreach (string wFile in Directory.GetFiles(wDst, "*.tiff")) { System.IO.File.Delete(wFile); }
            foreach (string wFile in Directory.GetFiles(wDst, "*.gif")) { System.IO.File.Delete(wFile); }
            foreach (string wFile in Directory.GetFiles(wDst, "*.bmp")) { System.IO.File.Delete(wFile); }

            foreach (string wDir in Directory.GetDirectories(wSrc, "*", SearchOption.AllDirectories))
            {
                string wSubFolder = wDir.Substring(wSrc.Length);
                if (!Directory.Exists(wDst + "\\" + wSubFolder))
                {
                    Directory.CreateDirectory(wDst + "\\" + wSubFolder);
                }
            }

            foreach (string wDir in Directory.GetFiles(wSrc, "*", SearchOption.AllDirectories))
            {
                string wFileName = wDir.Substring(wSrc.Length);
                try
                {
                    System.IO.File.Copy(wDir, wDst + "\\" + wFileName, true);
                }
                catch (System.IO.PathTooLongException)
                {
                    System.IO.File.Copy(wDir, wDst + "\\" + wFileName.Substring(50), true);
                }
            }

            foreach (string wDir in Directory.GetDirectories(wDst, "*", SearchOption.AllDirectories))
            {
                try
                {
                    if (Path.GetFileName(wDir) == "web_images")
                    {
                        Directory.Delete(wDir, true);
                    }
                    if (Path.GetFileName(wDir) == "web_thumbs")
                    {
                        Directory.Delete(wDir, true);
                    }                    
                }
                catch
                {

                }
            }            

            ConvertImages(wDst);

            foreach (string wFileName in Directory.GetFiles(wDst, "*.docx", SearchOption.AllDirectories))
            {
                try
                {
                    ConvertToHtml(wFileName, wContentPath);
                }
                catch { }
            }
            SiteStructure wSiteModel = new SiteStructure(wDst);
            SiteStructure.Instance = wSiteModel;
        }

        private static void ConvertImages(string wPath)
        {
            List<string> wFiles = new List<string>();
            wFiles.AddRange(Directory.GetFiles(wPath, "*.jpg", SearchOption.AllDirectories));
            wFiles.AddRange(Directory.GetFiles(wPath, "*.gif", SearchOption.AllDirectories));
            wFiles.AddRange(Directory.GetFiles(wPath, "*.jpeg", SearchOption.AllDirectories));
            wFiles.AddRange(Directory.GetFiles(wPath, "*.tiff", SearchOption.AllDirectories));
            wFiles.AddRange(Directory.GetFiles(wPath, "*.png", SearchOption.AllDirectories));

            foreach (string str in wFiles)
            {
                if (str.Contains("web_images")) continue;                
                if (str.Contains("web_thumbs")) continue;
                SaveAsJpeg(str, "web_images", 900);
                SaveAsJpeg(str, "web_thumbs_lg", 300);
                SaveAsJpeg(str, "web_thumbs", 70);
            }
        }        

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        public static byte [] SaveAsJpeg(Bitmap bmp)
        {
            ImageCodecInfo ec = GetEncoderInfo("image/jpeg");
            EncoderParameters parms = new EncoderParameters(1);
            parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 40);

            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, ec, parms);
                return ms.ToArray();
            }            
        }

        private static void SaveAsJpeg(string fromFile, string dstSubFolder, int wWidth)
        {
            using (System.Drawing.Image image = System.Drawing.Image.FromFile(fromFile))
            {

                ImageCodecInfo ec = GetEncoderInfo("image/jpeg");
                EncoderParameters parms = new EncoderParameters(1);
                parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 40);

                var ratio = (double)wWidth / image.Width;

                var newHeight = (int)(image.Height * ratio);

                var newImage = new Bitmap(wWidth, newHeight);
                using (var g = Graphics.FromImage(newImage))
                {
                    g.DrawImage(image, 0, 0, wWidth, newHeight);
                }

                string wFileName = Path.GetFileNameWithoutExtension(fromFile) + ".jpg";
                string wPath = fromFile.Substring(0, fromFile.Length - Path.GetFileName(fromFile).Length);
                if (!Directory.Exists(wPath + "\\" + dstSubFolder))
                {
                    Directory.CreateDirectory(wPath + "\\" + dstSubFolder);
                }
                System.IO.File.Delete(wPath + "\\" + dstSubFolder + "\\" + wFileName);
                newImage.Save(wPath + "\\" + dstSubFolder + "\\" + wFileName, ec, parms);
                newImage.Dispose();
            }
        }

        static private void ConvertToHtml(string wFileName, string wContentPath)
        {
            string wDirName = Path.GetDirectoryName(wFileName);
            string wFile = Path.GetFileNameWithoutExtension(wFileName);
            
            HtmlConverterHelper.ConvertToHtml(wFileName, wDirName);

            string wText = System.IO.File.ReadAllText(wDirName + "\\" + wFile + ".html");

            string wImagePath = wDirName + "\\" +  wFile + "_files/";
            wImagePath = wImagePath.Replace("\\\\", "\\");

            string wNewImagePath = "/Content/Word2Boot/" + wImagePath.Replace(wContentPath, "").Replace("\\", "/");

            string wNewText = wText.Replace(wImagePath, wNewImagePath);
            string text = PreMailer.Net.PreMailer.MoveCssInline(wNewText).Html;
            text = text.Substring(text.IndexOf("<body>") + 6);
            text = text.Substring(0, text.IndexOf("</body>"));

            text = ReplaceWithGallery(text, Path.GetDirectoryName(wFileName), wContentPath);    

            System.IO.File.WriteAllText(wDirName + "\\" + wFile + ".html", text);            
        }

        private static string ReplaceWithGallery(string str, string wRootPath, string wContentPath)
        {
            string wLowerCase = str.ToLower();
            int pos = -1;
            string wSize = "";
            while (wLowerCase.IndexOf(":gallery", pos + 1) > -1)
            {
                bool blnFullScreen = false;
                pos = wLowerCase.IndexOf(":gallery", pos + 1);

                int wLen = ":gallery".Length;
                string wPath = "";
                if (wLowerCase.IndexOf(":gallery-lg") == pos)
                {
                    blnFullScreen = true;
                    wLen = ":gallery-lg".Length;
                    wSize = "_lg";
                }
                if (wLowerCase[pos + wLen] == '-')
                {
                    int wEnd = wLowerCase.IndexOf(":", pos + 1);
                    if (wEnd > 0)
                    {
                        wPath = str.Substring(pos + wLen + 1, wEnd - (pos + wLen + 1));
                        wLen += wPath.Length + 2;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (wLowerCase[pos + wLen] == ':')
                {
                    wLen++;
                }
                else
                {
                    continue;
                }
                str = ReplaceWithHtml(str, pos, wLen, wRootPath + "\\" + wPath, blnFullScreen, wContentPath, wSize);
                wLowerCase = str.ToLower();
            }
            return str;
        }

        private static string ReplaceWithHtml(string str, int pos, int wLen, string wPath, bool blnFullScreen, string wContentPath, string wSize)
        {
            string wRet = str.Substring(0, pos);
            wRet += GenerateGallery(wPath, wContentPath, wSize);
            wRet += str.Substring(pos + wLen);

            return wRet;
        }

        private static string GenerateGallery(string wPath, string wContentPath, string size)
        {
            string wRet = "<div id=\"links\"><center>";
            string wRootPath = wPath.Replace(wContentPath, "/Content/Word2Boot/").Replace("\\", "/");
            try
            {
                if (Directory.Exists(wPath + "\\web_images"))
                {
                    foreach (string str in Directory.GetFiles(wPath + "\\web_images", "*.jpg", SearchOption.TopDirectoryOnly))
                    {
                        if (Path.GetFileName(str).StartsWith("apple-touch-icon")) continue;
                        string wFileName = Path.GetFileNameWithoutExtension(str);
                        wRet += string.Format(@"
                    <a href=""{1}/web_images/{0}.jpg"" title=""{0}"" data-gallery>
                            <img src=""{1}/web_thumbs{2}/{0}.jpg"" alt=""{0}"">
                    </a>
            ", wFileName, wRootPath, size);
                    }
                }
            }
            catch
            {
            }
            wRet += "</center></div>";
            return wRet;
        }

        //public void test()
        //{
        //    string wFileName = "";
        //    string wDirName = Path.GetDirectoryName(wFileName);
        //    string wFile = Path.GetFileNameWithoutExtension(wFileName);
        //    byte[] byteArray = System.IO.File.ReadAllBytes(wFileName);
        //    using (MemoryStream memoryStream = new MemoryStream())
        //    {
        //        memoryStream.Write(byteArray, 0, byteArray.Length);
        //        using (WordprocessingDocument doc =
        //            DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(memoryStream, true))
        //        {


        //            HtmlConverterSettings settings = new OpenXmlPowerTools.HtmlConverterSettings();
        //            settings.PageTitle = "";

        //            XElement html = HtmlConverter.ConvertToHtml(doc, settings);


        //            string text = PreMailer.Net.PreMailer.MoveCssInline(html.ToStringNewLineOnAttributes()).Html;
        //            text = text.Substring(text.IndexOf("<body>") + 6);
        //            text = text.Substring(0, text.IndexOf("</body>"));
        //            System.IO.File.WriteAllText(wDirName + "\\" + wFile + ".html", text.Trim(new char[] { ' ', '\t', '\n', '\r' }));
        //        }
        //    }
        //}
    }
}
